namespace SimpleWebServices.Web.UI.Html.Elements
{
    using System;
    using System.Xml;
    using System.Xml.Serialization;
    using SimpleWebServices.Data;

    [XmlRoot("input")]
    public class CheckBoxInput : Input, IXmlSerializable
    {
        public CheckBoxInput()
        {
        }

        public CheckBoxInput(Name id)
            : base(id)
        {
        }

        public bool Checked
        {
            get;
            set;
        }

        public override string Type
        {
            get
            {
                return "checkbox";
            }
        }

        public override IElement Deserialize(string name, string type, string xml)
        {
            IElement result = null;

            if ("input".Equals(name, StringComparison.OrdinalIgnoreCase) && this.Type.Equals(type, StringComparison.OrdinalIgnoreCase))
            {
                result = xml.Deserialize<CheckBoxInput>();
            }

            return result;
        }

        public override DataCollection ToDataCollection()
        {
            DataCollection result = new DataCollection();

            if (!this.Suppress && !string.IsNullOrEmpty(this.Name) && this.Checked)
            {
                result.Add(this.Name, this.Value);
            }

            return result;
        }

        public override void Update(Name name, string value)
        {
            if (this.Name == name)
            {
                this.Checked = true;
            }
        }

        public override void ReadXml(XmlReader reader)
        {
            base.ReadXml(reader);

            if (XmlNodeType.Element == reader.NodeType)
            {
                this.Checked = "checked".Equals(reader.GetAttribute("checked"), StringComparison.OrdinalIgnoreCase);
            }
        }

        public override void WriteXml(XmlWriter writer)
        {
            base.WriteXml(writer);

            if (this.Checked)
            {
                writer.WriteAttributeString("checked", "checked");
            }
        }
    }
}